import 'package:fish_redux/fish_redux.dart';
import 'package:flutter/material.dart' hide Action;
import 'package:kunlun_gas/AppViews/EngineerOrderView/model/meter_info_model.dart';
import 'package:kunlun_gas/app_files.dart';

import 'action.dart';
import 'state.dart';

Effect<EngineerMaterAddViewState> buildEffect() {
  return combineEffects(<Object, Effect<EngineerMaterAddViewState>>{
    EngineerMaterAddViewAction.onAdd: _onAdd,
    EngineerMaterAddViewAction.onDel: _onDel,
    EngineerMaterAddViewAction.onTapNumber: _onTapNumber,
    Lifecycle.initState: _initState,
  });
}

void _initState(Action action, Context<EngineerMaterAddViewState> ctx) async {
  ResultData listRes = await CommonNetWork.materialList(ctx.state.type);
  if (listRes.success) {
    List data = listRes.data['data'];
    ctx.state.materList = data
        .map<EngineerMaterList>((e) => EngineerMaterList.fromJson(e))
        .toList();
    if (ctx.state.selectList.isEmpty) {
      for (var item in ctx.state.materList){
        if (item.defaultMater) {
          item.number = 0;
          ctx.state.selectList.add(item);
        }
      }
    }

    ctx.dispatch(EngineerMaterAddViewActionCreator.onAction());
  }
}

void _onTapNumber(Action action, Context<EngineerMaterAddViewState> ctx) async {
  EngineerMaterList goodsModel = action.payload['model'];
  String type = action.payload['type'];
  if (type == '+') {
    goodsModel.number++;
    ctx.dispatch(EngineerMaterAddViewActionCreator.onAction());
  } else {
    if (goodsModel.number != 1) {
      goodsModel.number--;
      ctx.dispatch(EngineerMaterAddViewActionCreator.onAction());
    }
  }
}

void _onAdd(Action action, Context<EngineerMaterAddViewState> ctx) async {
  List<String> titles = ctx.state.materList.map<String>((e) => e.desc).toList();
  int res = await showModalBottomSheet(
      context: ctx.context,
      builder: (BuildContext context) {
        return CommonUtils.routeBuildPage(context, RoutePath.bottomSelectView,
            {'items': titles, 'title': '请选择材料'});
      },
      isScrollControlled: true,
      backgroundColor: Colors.transparent);
  if (res != null) {
    if (!ctx.state.selectList.contains(ctx.state.materList[res])) {
      ctx.state.materList[res].number = 1;
      ctx.state.selectList.add(ctx.state.materList[res]);
      ctx.dispatch(EngineerMaterAddViewActionCreator.onAction());
    }
    else {
      for (var item in ctx.state.selectList) {
        if (item.itemId ==  ctx.state.materList[res].itemId ) {
          item.number ++;
        }
      }
      ctx.dispatch(EngineerMaterAddViewActionCreator.onAction());
    }
  }
}

void _onDel(Action action, Context<EngineerMaterAddViewState> ctx) async {
  print('1212');
  ctx.state.selectList.remove(action.payload);
  ctx.dispatch(EngineerMaterAddViewActionCreator.onAction());
}
